import React, {Component} from 'react';
import styles from './index.less';
import CSSModules from 'react-css-modules';
import {
  Row,
  Col,
  Badge,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Table,
  Modal,
  Menu,
  Avatar,
  Divider,
  Popconfirm,
  notification,
  Pagination,
} from 'antd';
const FormItem = Form.Item;
const {Option} = Select;
const {Search} = Input;

import UserGroupModal from './userGroupModal';

import {
  GET_USER_LIST_URL,
  FORBID_USER_URL,
  MODIFY_USER_ROLE_URL,
} from 'constant/url';
import myaxios, {get, put, post, deleteAxios} from 'common/fetch';

class UserList extends Component {
  state = {
    selectedRowKeys: [],
    showModal: false,
    showSelectUserGroupModal: false,
    page: 1,
    size: 10,
    totalSize: 0,
    filteredValue: ['0', '1'],
    namePrefix: '',
    list: [],
    currentUserGroup: undefined,
    handleUid: undefined, // 当前操作的uid(加入分组、封禁等功能)
  };
  getQuery() {
    let query = {
      page: this.state.page,
      size: this.state.size,
      namePrefix: this.state.namePrefix,
    };
    return query;
  }
  onPageNoChange(page, size) {
    this.setState(
      {
        page,
      },
      () => {
        let query = this.getQuery();
        this.getUserList(query);
      },
    );
  }
  componentDidMount() {
    this.getUserList(this.getQuery());
  }
  //获取运营列表
  getUserList(query) {
    get(GET_USER_LIST_URL, query).then(res => {
      this.setState({
        list: res.list,
        totalSize: res.total,
      });
    });
  }
  handleRowSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({selectedRowKeys});
  };
  createUserGroup = () => {
    this.setState({showModal: true});
  };
  showSelectUserGroup = uid => {
    this.setState({
      showSelectUserGroupModal: true,
      handleUid: uid,
    });
  };
  handleCancel = () => {
    this.setState({
      showModal: false,
    });
  };
  hideSelectUserGroup = () => {
    this.setState({showSelectUserGroupModal: false});
  };
  // 修改modal内用户组
  handleUserGroupChange = value => {
    this.setState({currentUserGroup: value});
  };
  // 添加用户组
  addGroup = () => {
    let uid = this.state.handleUid;
    this.setState(
      {
        showSelectUserGroupModal: false,
        handleUid: undefined,
      },
      () => {
        post(MODIFY_USER_ROLE_URL, {
          role: this.state.currentUserGroup,
          uid,
        }).then(res => {
          notification.success({
            message: '加入用户组',
            description: `${uid} 加入用户组 ${
              this.state.currentUserGroup == 1 ? '编辑' : '普通客户'
            }`,
            duration: 2,
          });
          this.getUserList(this.getQuery());
        });
      },
    );
  };
  queryUserListByNamePrefix = value => {
    this.setState(
      {
        namePrefix: value,
      },
      () => {
        let query = this.getQuery();
        this.getUserList(query);
      },
    );
  };
  // 封禁用户
  forbidUser = uid => {
    post(FORBID_USER_URL, {userIds: uid}).then(res => {
      notification.success({
        message: '封禁用户',
        description: `成功封禁 ${uid}`,
        duration: 2,
      });
      this.getUserList(this.getQuery());
    });
  };

  handleOk = () => {
    this.refs.createUserGroupForm.validateFields((err, values) => {
      if (!err) {
        this.setState({
          showModal: false,
        });
      }
    });
  };
  render() {
    const that = this;
    const {
      selectedRowKeys,
      showModal,
      showSelectUserGroupModal,
      list,
      page,
      size,
      totalSize,
    } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.handleRowSelectChange,
      getCheckboxProps: record => ({
        disabled: record.disabled,
      }),
    };

    // 用户操作actions button
    const MoreBtn = props => (
      <Dropdown
        placement="bottomCenter"
        overlay={
          <Menu>
            <Menu.Item>
              <a
                onClick={ev => {
                  that.showSelectUserGroup(props.uid);
                }}>
                修改角色
              </a>
            </Menu.Item>
            <Menu.Item>
              <Popconfirm
                title="确认封禁用户？封禁后该用户在app端将被禁言。"
                placement="topRight"
                okText="确认"
                cancelText="取消"
                onConfirm={() => {
                  that.forbidUser(props.uid);
                }}>
                <a>封禁</a>
              </Popconfirm>
            </Menu.Item>
          </Menu>
        }>
        <a>
          更多 <Icon type="down" />
        </a>
      </Dropdown>
    );
    const status = ['正常', '已封禁'],
      statusMap = ['success', 'error'];
    // 用户列表内容
    const columns = [
      {
        title: '用户头像',
        dataIndex: 'userLogo',
        render: (text, record) => (
          <Avatar src={record.avatarUrl} shape="square" size="large" />
        ),
      },
      {
        title: '用户名',
        dataIndex: 'userName',
        //render: (text, record) => <a href={`#user/userDetail/${record.uid}`}>{text}</a>,
        render: (text, record) => <a>{text}</a>,
      },
      {
        title: '手机号码',
        dataIndex: 'mobile',
        //render: (text, record) => <a href={`#user/userDetail/${record.uid}`}>{text}</a>,
        render: (text, record) => (text ? text : '--'),
      },
      {
        title: '角色',
        dataIndex: 'role',
        //render: (text, record) => <a href={`#user/userDetail/${record.uid}`}>{text}</a>,
        render: (text, record) => (text == 1 ? '编辑' : '普通客户'),
      },
      {
        title: '注册时间',
        dataIndex: 'createTime',
      },
      {
        title: '状态',
        dataIndex: 'status',
        render(val) {
          return <Badge status={statusMap[val]} text={status[val]} />;
        },
      },
      {
        title: '操作',
        dataIndex: 'operate',
        width: 200,
        fixed: 'right',
        render: (text, record) => {
          const {uid} = record;
          return (
            <div>
              <a
                onClick={ev => {
                  that.showSelectUserGroup(uid);
                }}>
                修改角色
              </a>
              <Divider type="vertical" />
              <MoreBtn uid={uid} />
            </div>
          );
        },
      },
    ];

    return (
      <div className={`${styles.content} ${styles['home-container']}`}>
        <Card bordered={false} style={{flex: 'auto'}}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>
              <Form layout="inline">
                <Row gutter={48}>
                  {/*
                  <Col md={8} sm={24}>
                    <FormItem label="选择用户组">
                      <Select placeholder="请选择" style={{width: '100%'}}>
                        <Option value="0">KOL</Option>
                        <Option value="1">分组二</Option>
                      </Select>
                    </FormItem>
                  </Col>

                */}
                  <Col md={8} sm={24}>
                    <Search
                      className={styles.extraContentSearch}
                      placeholder="请输入用户名"
                      enterButton="查询"
                      onSearch={this.queryUserListByNamePrefix}
                    />
                  </Col>
                </Row>
              </Form>
            </div>
            <div className={styles.tableListOperator}>
              {/*
              <Button icon="plus" type="primary" onClick={this.createUserGroup}>
                新建用户组
              </Button>
              */}
              <Modal
                visible={showModal}
                title="新建用户组"
                onOk={this.handleOk}
                onCancel={this.handleCancel}
                footer={[
                  <Button key="back" onClick={this.handleCancel}>
                    取消
                  </Button>,
                  <Button key="submit" type="primary" onClick={this.handleOk}>
                    提交
                  </Button>,
                ]}>
                <WrappedCreateUserGroupForm ref="createUserGroupForm" />
              </Modal>
              <UserGroupModal
                visible={showSelectUserGroupModal}
                onOk={this.addGroup}
                onCancel={this.hideSelectUserGroup}
                defaultGroup={this.state.currentUserGroup}
                selectOnChange={this.handleUserGroupChange}
              />
              {selectedRowKeys.length > 0 && (
                <span>
                  <Button>修改角色</Button>
                  <Button>封禁</Button>
                </span>
              )}
            </div>
            <Table
              scroll={{x: 1000}}
              rowKey={(record, index) => index}
              dataSource={list}
              columns={columns}
              rowSelection={rowSelection}
              pagination={false}
            />
            <div className={styles['page-wrap'] + ' clearfix'}>
              <div className={styles['page-l-wrap']}>
                <span className={styles['mt']}>总共：{totalSize}条</span>
              </div>
              <div className={styles['page-r-wrap']}>
                <Pagination
                  defaultCurrent={1}
                  defaultPageSize={20}
                  current={page}
                  pageSize={size}
                  total={totalSize}
                  onChange={this.onPageNoChange.bind(this)}
                />
              </div>
            </div>
          </div>
        </Card>
      </div>
    );
  }
}

class CreateUserGroupForm extends Component {
  render() {
    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 6},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 14},
      },
    };
    const {getFieldDecorator} = this.props.form;
    return (
      <Form>
        <FormItem {...formItemLayout} label="用户组名称" hasFeedback>
          {getFieldDecorator('proName', {
            rules: [
              {
                required: true,
                message: '请输入用户组名',
              },
            ],
          })(<Input />)}
        </FormItem>
      </Form>
    );
  }
}

const WrappedCreateUserGroupForm = Form.create()(CreateUserGroupForm);

export default CSSModules(UserList, styles);
